package com.feihao.zhou.service;

import com.feihao.zhou.bean.Student;
import com.feihao.zhou.bean.User;
import com.feihao.zhou.dao.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentService {

    public Boolean CheckUser(String username, String password) {
        try {
            InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

            User user = mapper.cheekUser(username, password);
            if (user != null) {
                return true;
            }
            is.close();
            sqlSession.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果没有，则返回false
        return false;
    }

    public List<Student> findStudent(String name, String age) {
        try {
            InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

            List<Student> studentList = mapper.findStudent(name, age);
            for (Student student : studentList) {
                System.out.println(student);
            }

            is.close();
            sqlSession.close();

            return studentList;


        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果没有，则返回false
        return null;
    }
}
